 ///
 /// @file    Singleton1.cc
 /// @author  lemon(haohb13@gmail.com)
 /// @date    2023-04-28 14:51:19
 ///
 
#include <iostream>
using std::cout;
using std::endl;

//需求：单例对象能自动回收


class Singleton
{
public:
	static Singleton * getInstance()
	{
		if(nullptr == _pInstance) {
			_pInstance = new Singleton();
		}
		return _pInstance;
	}

	static void destroy()
	{
		if(_pInstance) {
			delete _pInstance;
			_pInstance = nullptr;
		}
	}

private:
	Singleton() {	cout << "Singleton()" << endl;	}
	~Singleton() {	cout << "~Singleton()" << endl;	}

	friend class AutoRelease;
private:
	static Singleton * _pInstance;
	int _data;
};

Singleton * Singleton::_pInstance = nullptr;

class AutoRelease
{
public:
	AutoRelease(Singleton *p)
	: _p(p)
	{	cout << "AutoRelease(Singleton*)" << endl;	}

	~AutoRelease() {
		cout << "~AutoRelease()" << endl;
		if(_p) {
			delete _p;
			_p = nullptr;
		}
	}

private:
	Singleton * _p;
};
 
void test0() 
{
	//AutoRelease类专为Singleton而生,
	//既然这样，就可以考虑将其设计为嵌套类
	AutoRelease au(Singleton::getInstance());
	Singleton * p1 = Singleton::getInstance();
	Singleton * p2 = Singleton::getInstance();
	cout << "p1:" << p1 << endl;
	cout << "p2:" << p2 << endl;

	//Singleton::destroy();
} 
 
int main(void)
{
	test0();
	return 0;
}
